package com.hbase.mapreduce;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;

public class HBaseUtil {

	private static Configuration hbaseConfiguration = null;
	private static Connection connection = null;

	static {
		hbaseConfiguration = HBaseConfiguration.create();
		hbaseConfiguration.set("hbase.zookeeper.property.clientPort", "2181");
		hbaseConfiguration.set("hbase.zookeeper.quorum", "192.168.51.253");
		hbaseConfiguration.set("hbase.master", "192.168.51.253:60000");
		try {
			connection = ConnectionFactory.createConnection(hbaseConfiguration);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void createTable(TableName tableName, byte[]... columnFamilies) {
		try {
			Admin admin = connection.getAdmin();
			HTableDescriptor desc = new HTableDescriptor(tableName);
			for (byte[] cf : columnFamilies) {
				desc.addFamily(new HColumnDescriptor(cf));
			}
			admin.createTable(desc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Table getTable(TableName tableName) throws IOException {
		return connection.getTable(tableName);
	}

	public static void close() throws IOException {
		connection.close();
	}
}
